package cn.home.bootstrap.p2p;

import com.rabbitmq.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 单个生产者对对个消费者，消费者
 */
public class Recv {
  private final static String IP = "127.0.0.1";
  private final static int  PORT = 5672;
  private final static String USER_NAME = "donaldhan";
  private final static String PASSWORD = "123456";
  private final static Logger log = LoggerFactory.getLogger(Send.class);
  private final static String QUEUE_NAME = "hello";

  public static void main(String[] argv) throws Exception {
    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(IP);
    factory.setPort(PORT);
   /* factory.setUsername(USER_NAME);
    factory.setPassword(PASSWORD);*/
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    /*
     * @param queue the name of the queue
     * @param durable true if we are declaring a durable queue (the queue will survive a server restart)
     * @param exclusive true if we are declaring an exclusive queue (restricted to this connection)
     * @param autoDelete true if we are declaring an autodelete queue (server will delete it when no longer in use)
     * @param arguments other properties (construction arguments) for the queue
     */
    channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    log.info(" Consumer Waiting for messages...");
    Consumer consumer = new DefaultConsumer(channel) {
      @Override
      public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
          throws IOException {
        String message = new String(body, "UTF-8");
        log.info(" Consumer Received  message from  Queue({}),{}",QUEUE_NAME,message);
      }
    };
    /*
     * @param queue the name of the queue
     * @param autoAck true if the server should consider messages
     * acknowledged once delivered; false if the server should expect
     * explicit acknowledgements
     * @param callback an interface to the consumer object
     */
    //自动回复
    channel.basicConsume(QUEUE_NAME, true, consumer);
  }
}
